/**
 * 
 */
package com.geezdata.cps.sdk3rd.wechat.method;

import java.io.UnsupportedEncodingException;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.geezdata.cps.base.utils.HttpClientUtil;
import com.geezdata.cps.sdk3rd.wechat.request.WechatQrCodePageReqeust;
import com.geezdata.cps.sdk3rd.wechat.response.WechatQrCodePageResult;
import com.google.common.collect.Maps;

/**
 * @author tfwan
 * @date 创建时间：2018年7月2日 下午4:32:39
 *
 */
public class WechatQrCodePage extends BaseWechat implements Wechat<WechatQrCodePageReqeust, WechatQrCodePageResult> {
	private static final String QRCODE_URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=";
	
	@Override
	public WechatQrCodePageResult execute(WechatQrCodePageReqeust request) {
		WechatQrCodePageResult wechatQrCodePageResult = new WechatQrCodePageResult();
		Map<String, Object> params = prepareParams(request);
		byte[] rspStr =null;
		rspStr = HttpClientUtil.post(QRCODE_URL + request.getToken(), JSONObject.toJSONString(params));
		if(rspStr == null) {
			return null;
		}
		try {
			String res = new String(rspStr,"UTF-8");
			if(isExpire(res)) {
				wechatQrCodePageResult.setExpired(true);
				return wechatQrCodePageResult;
			}
		} catch (UnsupportedEncodingException e) {
		}
		
		
		wechatQrCodePageResult.setQrCode(rspStr);
		return wechatQrCodePageResult;
	}

	private Boolean isExpire( String res) {
		return res.contains("40001") || res.contains("42001");
	}
	private Map<String, Object> prepareParams(WechatQrCodePageReqeust request) {
		Map<String, Object> map = Maps.newHashMap();
		if(StringUtils.isNotBlank(request.getScene())) {
			map.put("scene", request.getScene());
		}
		if(StringUtils.isNotBlank(request.getPage())) {
			map.put("page", request.getPage());
		}
		if(request.getWidth()!=null) {
			map.put("width", request.getWidth());
		}
		if(request.getAutoColor()!=null) {
			map.put("auto_color", request.getAutoColor());
		}
		if(request.getIsHyaline()!=null) {
			map.put("is_hyaline", request.getIsHyaline());
		}
		return map;
	}
}
